<%-- 
    Document   : articulo
    Created on : Jun 29, 2013, 10:09:24 PM
    Author     : Gustavo Palacios
--%>

<%@page import="java.io.IOException"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="javax.swing.table.DefaultTableModel"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
    <head>
        <!--
		Charisma v1.0.0

		Copyright 2012 Muhammad Usman
		Licensed under the Apache License v2.0
		http://www.apache.org/licenses/LICENSE-2.0

		http://usman.it
		http://twitter.com/halalit_usman
	-->
        <meta charset="utf-8">
        <title>EduShare - Nuevo Artículo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Charisma, a fully featured, responsive, HTML5, Bootstrap admin template.">
        <meta name="author" content="Muhammad Usman">

        <!-- The styles -->
        <link id="bs-css" href="css/bootstrap-cerulean.css" rel="stylesheet">
        <style type="text/css">
            body {
                padding-bottom: 40px;
            }
            .sidebar-nav {
                padding: 9px 0;
            }
        </style>
        <link href="css/bootstrap-responsive.css" rel="stylesheet">
        <link href="css/charisma-app.css" rel="stylesheet">
        <link href="css/jquery-ui-1.8.21.custom.css" rel="stylesheet">
        <link href='css/fullcalendar.css' rel='stylesheet'>
        <link href='css/fullcalendar.print.css' rel='stylesheet'  media='print'>
        <link href='css/chosen.css' rel='stylesheet'>
        <link href='css/uniform.default.css' rel='stylesheet'>
        <link href='css/colorbox.css' rel='stylesheet'>
        <link href='css/jquery.cleditor.css' rel='stylesheet'>
        <link href='css/jquery.noty.css' rel='stylesheet'>
        <link href='css/noty_theme_default.css' rel='stylesheet'>
        <link href='css/elfinder.min.css' rel='stylesheet'>
        <link href='css/elfinder.theme.css' rel='stylesheet'>
        <link href='css/jquery.iphone.toggle.css' rel='stylesheet'>
        <link href='css/opa-icons.css' rel='stylesheet'>
        <link href='css/uploadify.css' rel='stylesheet'>

        <!-- The HTML5 shim, for IE6-8 support of HTML5 elements -->
        <!--[if lt IE 9]>
	  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->

        <!-- The fav icon -->
        <link rel="shortcut icon" href="img/favicon.ico">

    </head>

    <body>
        <!-- topbar starts -->
        <div class="navbar">
            <div class="navbar-inner">
                <div class="container-fluid">
                    <a class="btn btn-navbar" data-toggle="collapse" data-target=".top-nav.nav-collapse,.sidebar-nav.nav-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </a>
                    <a class="brand" href="index.html"> <img alt="Charisma Logo" src="img/logo20.png" /> <span>EduShare</span></a>




                    <!-- user dropdown starts -->
                    <div class="btn-group pull-right" >

                        <%
                            String correoUsuario = null;
                            //si hay una sesion activa
                            if (session != null && session.getAttribute("correo") != null && session.getAttribute("tipoUsuario").toString().equals("publicador")) {
                                    
                                //tomar el valor del correo del usuario
                                correoUsuario = session.getAttribute("correo").toString();
                                //colocar el html para mostra el usuario y el dropdown
                        %>
                        <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
                            <i class="icon-user"></i><span class="hidden-phone"><%= correoUsuario%></span>
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a href="perfil.jsp">Perfil</a></li>
                            <li class="divider"></li>
                            <li><a href="index.jsp?cs=true">Logout</a></li>
                        </ul>
                        <%} //si no hay una session activa
                        else {%>
                        <a class="btn dropdown-toggle" data-toggle="dropdown" href="login.jsp">
                            <i class="icon-user"></i><span class="hidden-phone">Login/Registro</span>
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a href="login.jsp">Login</a></li>                            
                        </ul>
                        <%}%>
                    </div>
                    <!-- user dropdown ends -->

                    
                </div>
            </div>
        </div>
        <!-- topbar ends -->
        <div class="container-fluid">
            <div class="row-fluid">

                <!-- left menu starts -->
                <div class="span2 main-menu-span">
                    <div class="well nav-collapse sidebar-nav">
                        <ul class="nav nav-tabs nav-stacked main-menu">
                            <li class="nav-header hidden-tablet">Menú</li>
                            <li><a class="ajax-link" href="index.jsp"><i class="icon-home"></i><span class="hidden-tablet">Inicio</span></a></li>
                            <!-- href de form.html a articulo.html-->
                            <li><a class="ajax-link" href="articulo.jsp"><i class="icon-edit"></i><span class="hidden-tablet">Nuevo Artículo</span></a></li>
                            <!-- href de chart.html a reporte.html-->
                            <li><a class="ajax-link" href="reporte.jsp"><i class="icon-list-alt"></i><span class="hidden-tablet">Reportes</span></a></li>
                            <!-- href de table.html a busqueda.html-->
                            <li><a class="ajax-link" href="busqueda.jsp"><i class="icon-align-justify"></i><span class="hidden-tablet">Buscar</span></a></li>
                            <!-- (agregado) href a administrar.html-->
                            <li><a class="ajax-link" href="administrar.jsp"><i class="icon-align-justify"></i><span class="hidden-tablet">Administrar</span></a></li>

                        </ul>

                    </div><!--/.well -->
                </div><!--/span-->
                <!-- left menu ends -->

                <noscript>
                    <div class="alert alert-block span10">
                        <h4 class="alert-heading">Warning!</h4>
                        <p>You need to have <a href="http://en.wikipedia.org/wiki/JavaScript" target="_blank">JavaScript</a> enabled to use this site.</p>
                    </div>
                </noscript>

                <div id="content" class="span10">
                    <!-- content starts -->


                    <div>
                        <ul class="breadcrumb">
                            <li>
                                <a href="#">Inicio</a> <span class="divider">/</span>
                            </li>
                            <li>
                                <a href="#">Nuevo Artículo</a>
                            </li>
                        </ul>
                    </div>

                    <div class="row-fluid sortable">
                        <div class="box span12">
                            <div class="box-header well" data-original-title>
                                <h2><i class="icon-edit"></i> </h2>
                                <div class="box-icon">
                                    <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a>
                                    <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a>
                                    <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a>
                                </div>
                            </div>
                            <div class="box-content">
                                <form class="form-horizontal">
                                    <fieldset>
                                        <legend>Publicar Artículo</legend>
                                        <div class="control-group">
                                            <label class="control-label" for="typeahead">Título</label>
                                            <div class="controls">
                                                <input type="text" name="Titulo" value="" />

                                            </div>

                                        </div>

                                           <%
                                            String user = "sql312735";
                                            String clave = "sH9!yN8%";
                                            String ruta = "jdbc:mysql://sql3.freemysqlhosting.net:3306/sql312735";
                                    Connection conexion = null;
                                    Statement Sentencias = null;
                                    Statement getId=null;
                                    Statement InsertCategoria=null;
                                    Statement VerificarCategoria=null;
                                    Statement getCategoria=null;

                                    ResultSet Categorias=null;
                                    ResultSet tabla = null;
                                    ResultSet id_categoria=null;
                                        
                                     try {
                                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                                        conexion = DriverManager.getConnection(ruta,user, clave);
                                        Sentencias = conexion.createStatement();
                                        getId=conexion.createStatement();
                                        InsertCategoria=conexion.createStatement();
                                        getCategoria=conexion.createStatement();
                                                VerificarCategoria=conexion.createStatement();
                                    } catch (Exception e) {
                                        out.println("<script>alert('Error de Conexion " + e.getMessage() + "')</script>");
                                    }
                                            Categorias = getCategoria.executeQuery("select id_categoria,nombre from CATEGORIA");

                                            out.print(" <div class=\"control-group\"> "+
                                            "<label class=\"control-label\" for=\"selectError1\">Categoria</label> "+
                                            "<div class=\"controls\">" +
                                               " <select id=\"selectError1\" name=\"seleccion\" multiple data-rel=\"chosen\">");

                                            while (Categorias.next()) {

                                                out.print("<option>"+Categorias.getString("nombre")+"</option>");

                                             }
                                                out.print("   </select>");


                                            %>
                                       
                                                    
                                             

                                            </div>
                                        </div>



                                        <div class="control-group">
                                            <label class="control-label" for="textarea2">Contenido</label>
                                            <div class="controls">
                                                <textarea name="contenido" class="cleditor" rows="4" cols="20">
                                                </textarea>
                                            </div>
                                        </div>

                                        <div class="control-group">
                                            <label class="control-label" for="date01">Publicar en fecha</label>
                                            <div class="controls">
                                                <input type="text" class="input-xlarge datepicker" id="date01" value="02/16/12">
                                                <button type="submit" class="btn btn-primary">Programar</button>
                                            </div>
                                        </div>

                                        <div class="form-actions">
                                            <input type="submit" name="publicar" value="Publicar Ahora" class="btn btn-primary" />
                                            <button type="reset" class="btn">Cancelar</button>



                                        </div>
                                    </fieldset>
                                </form>

                            </div>
                        </div><!--/span-->

                    </div><!--/row-->

                    <%
                                /*
                                if (request.getParameter("Login") != null) {
                                String user = "root";
                                String clave = "123";
                                String ruta = "jdbc:mysql://10.0.0.4:3306/ayd2bd";
                                Connection conexion = null;
                                Statement Sentencias = null;
                                ResultSet tabla = null;
                                try {
                                Class.forName("com.mysql.jdbc.Driver").newInstance();
                                conexion = DriverManager.getConnection(ruta, user, clave);
                                Sentencias = conexion.createStatement();
                                } catch (Exception e) {
                                out.println("<script>alert('Error de Conexion')</script>");
                                }




                                int b = 0;
                                String us = null;
                                String pa = null;
                                String tipo = null;

                                String usuario = request.getParameter("usuario");
                                String passs = request.getParameter("pass");
                                out.print(usuario);
                                out.print(passs);
                                //la consulta SQL
                                try {
                                tabla = Sentencias.executeQuery("select email,password, tipo from usuario where email='" + usuario + "' ");

                                while (tabla.next()) {
                                us = tabla.getString("email");
                                pa = tabla.getString("password");
                                tipo = tabla.getString("tipo");
                                out.print(us);
                                out.print(pa);
                                if (us.equals(usuario) && pa.equals(passs)) {
                                b = 1;
                                //en esta linea agrego la variable de session correo
                                session.setAttribute("correo", us);
                                //en esta linea agrego la variable de session tipo
                                session.setAttribute("tipoUsuario", tipo);

                                response.sendRedirect("Principal.jsp");
                                } else {
                                out.println("<script>alert('Datos Erroneos  ')</script>");
                                }

                                }
                                //luego comparamos si es uno es usuario existente y bien validado sino error


                                } catch (Exception e) {
                                out.println("<script>alert('Error')</script>");
                                e.printStackTrace();
                                }



                                }
                                 * */

                     
try{
                                 if (request.getParameter("publicar") != null) {


                                                                                               
                                    Date dNow = new Date();
                                    String HoraFecha;
                                    SimpleDateFormat ft =
                                            new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                    String currentDate = ft.format(dNow);

                                    String titulo = request.getParameter("Titulo"); // OBTENGO TITULO
                                    HoraFecha = currentDate; //OBTENGO FECHA DE PUBLICACION
                                    
                                     if( request.getParameter("Titulo")!=null&& request.getParameter("contenido")!=null && request.getParameter("seleccion")!=null )
                                        {
                                      
                                    // out.println("<script>alert('"+currentDate+"')</script>");

                                    FileWriter fichero = null;
                                    String datos = request.getParameter("contenido");
                                    tabla= getId.executeQuery("SELECT MAX(id_articulo) AS id FROM ARTICULO");

                                    
                                     int maxId=0;
                                        while (tabla.next()) {
                                    maxId=tabla.getInt("id")+1;
                                  // out.print("antes2");
                                   }
                                    try {
// Creas la instancia del fichero
                    
                                        String Ubicacion = getServletContext().getRealPath("/") + "Articulos/"+String.valueOf(maxId)+".txt";
                                        fichero = new FileWriter(Ubicacion);
// El carácter \r\n es el que hace que salte una linia en el fichero después de escribir
                                        fichero.write(datos + "\r\n");
// Cierras el fichero
                                        fichero.close();
                                       String usuario= (String) session.getAttribute("id_usuario");
                                     //  out.print("INSERT INTO `articulo` ( `titulo`, `punteo`, `fecha_hora_publicacion`, `ubicacion_actual`, `descripcion`, `id_usuario`) VALUES ('" + titulo + "', '0', '" + HoraFecha + "', '"+String.valueOf(maxId)+".txt', 'informatica', '1');");
                                      Sentencias.executeUpdate("INSERT INTO `ARTICULO` ( `titulo`,  `fecha_hora_publicacion`, `ubicacion_actual`, `descripcion`, `id_usuario`,`punteo`) VALUES ('" + titulo + "',  '" + HoraFecha + "', '"+String.valueOf(maxId)+".txt', 'informatica', "+usuario+",'0');");

                                      String[] Categoria = request.getParameterValues("seleccion");

                                       for(int i=0;i<Categoria.length;i++)
                                        {
                                   id_categoria=VerificarCategoria.executeQuery("SELECT id_categoria from CATEGORIA where nombre='"+Categoria[i]+"'");

                                        while (id_categoria.next()) {
                                        out.print("INSERT INTO ETIQUETA (id_articulo, id_categoria) values ("+String.valueOf(maxId)+","+id_categoria.getString("id_categoria")+");");
                                        InsertCategoria.executeUpdate("INSERT INTO ETIQUETA (id_articulo, id_categoria) values ("+String.valueOf(maxId)+","+id_categoria.getString("id_categoria")+");");
                                       }
                                            out.print(Categoria[i]);

                                        }

                                        out.println("<script>alert('Articulo Publicado Exitosamente!')</script>");
                                    } catch (Exception ioe) {
                                        out.println("<script>alert('" + ioe.getMessage() + "')</script>");
// Aqui pones lo que quieres que haga cuando se da una excepción de escritura
                                    }   
                                    }
                                    else
                                        {
                           out.println("<script>alert('Ingrese Datos')</script>");

                                        }

                                }

                                }
                                catch(Exception e)
                                        {
                                    
                                      }


                    %>
                    <!-- PARA EDITARRRRRRRRRRRRRRRRRRRRRRRRRRR-->






                    <!-- content ends -->
                </div><!--/#content.span10-->
            </div><!--/fluid-row-->

            <hr>

            <div class="modal hide fade" id="myModal">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h3>Settings</h3>
                </div>
                <div class="modal-body">
                    <p>Here settings can be configured...</p>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn" data-dismiss="modal">Close</a>
                    <a href="#" class="btn btn-primary">Save changes</a>
                </div>
            </div>

            <footer>
                <p class="pull-left">&copy; <a href="http://usman.it" target="_blank">Muhammad Usman</a> 2012</p>
                <p class="pull-right">Powered by: <a href="http://usman.it/free-responsive-admin-template">Charisma</a></p>
            </footer>

        </div><!--/.fluid-container-->

        <!-- external javascript
	================================================== -->
        <!-- Placed at the end of the document so the pages load faster -->

        <!-- jQuery -->
        <script src="js/jquery-1.7.2.min.js"></script>
        <!-- jQuery UI -->
        <script src="js/jquery-ui-1.8.21.custom.min.js"></script>
        <!-- transition / effect library -->
        <script src="js/bootstrap-transition.js"></script>
        <!-- alert enhancer library -->
        <script src="js/bootstrap-alert.js"></script>
        <!-- modal / dialog library -->
        <script src="js/bootstrap-modal.js"></script>
        <!-- custom dropdown library -->
        <script src="js/bootstrap-dropdown.js"></script>
        <!-- scrolspy library -->
        <script src="js/bootstrap-scrollspy.js"></script>
        <!-- library for creating tabs -->
        <script src="js/bootstrap-tab.js"></script>
        <!-- library for advanced tooltip -->
        <script src="js/bootstrap-tooltip.js"></script>
        <!-- popover effect library -->
        <script src="js/bootstrap-popover.js"></script>
        <!-- button enhancer library -->
        <script src="js/bootstrap-button.js"></script>
        <!-- accordion library (optional, not used in demo) -->
        <script src="js/bootstrap-collapse.js"></script>
        <!-- carousel slideshow library (optional, not used in demo) -->
        <script src="js/bootstrap-carousel.js"></script>
        <!-- autocomplete library -->
        <script src="js/bootstrap-typeahead.js"></script>
        <!-- tour library -->
        <script src="js/bootstrap-tour.js"></script>
        <!-- library for cookie management -->
        <script src="js/jquery.cookie.js"></script>
        <!-- calander plugin -->
        <script src='js/fullcalendar.min.js'></script>
        <!-- data table plugin -->
        <script src='js/jquery.dataTables.min.js'></script>

        <!-- chart libraries start -->
        <script src="js/excanvas.js"></script>
        <script src="js/jquery.flot.min.js"></script>
        <script src="js/jquery.flot.pie.min.js"></script>
        <script src="js/jquery.flot.stack.js"></script>
        <script src="js/jquery.flot.resize.min.js"></script>
        <!-- chart libraries end -->

        <!-- select or dropdown enhancer -->
        <script src="js/jquery.chosen.min.js"></script>
        <!-- checkbox, radio, and file input styler -->
        <script src="js/jquery.uniform.min.js"></script>
        <!-- plugin for gallery image view -->
        <script src="js/jquery.colorbox.min.js"></script>
        <!-- rich text editor library -->
        <script src="js/jquery.cleditor.min.js"></script>
        <!-- notification plugin -->
        <script src="js/jquery.noty.js"></script>
        <!-- file manager library -->
        <script src="js/jquery.elfinder.min.js"></script>
        <!-- star rating plugin -->
        <script src="js/jquery.raty.min.js"></script>
        <!-- for iOS style toggle switch -->
        <script src="js/jquery.iphone.toggle.js"></script>
        <!-- autogrowing textarea plugin -->
        <script src="js/jquery.autogrow-textarea.js"></script>
        <!-- multiple file upload plugin -->
        <script src="js/jquery.uploadify-3.1.min.js"></script>
        <!-- history.js for cross-browser state change on ajax -->
        <script src="js/jquery.history.js"></script>
        <!-- application script for Charisma demo -->
        <script src="js/charisma.js"></script>


    </body>
</html>
